/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ge.info.sip;

import ge.info.domain.AbonentFound;
import ge.info.domain.DbExecutor;
import ge.info.domain.Mymobile;
import java.io.PrintWriter;
import ge.info.logging.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author koka
 */
public class ErikServlet extends HttpServlet
{

    public static final String callStart = "start";
    public static final int callTypeOrganization = 3;
    public static final int callTypeMobile = -3;
    public static final int callTypeMobitel = -7;
    public static final int callTypeNoncharge = -8;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest req, HttpServletResponse response)
            throws ServletException, IOException
    {

        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        SessionMap currentSessions = (SessionMap) springContext.getBean("CurrentSessions");
        SessionMap previosSessions = (SessionMap) springContext.getBean("PreviousSessions");

        try
        {
            String userName = null;
            String comp = null;
            String phone = null;
            String type = null;
            String ip = null;

            int ampersand = -1;

             ip = req.getRemoteAddr();

            if ((userName = req.getParameter("userName")) != null &&
                    //                (callID = req.getParameter("callID")) != null &&
                    (phone = req.getParameter("phone")) != null &&
                    (ampersand = phone.indexOf("A")) > 0 &&
                    (type = req.getParameter("type")) != null &&
                    (comp = req.getParameter("who")) != null)

                    // && (ip = req.getParameter("ip")) != null)
            {
                DbExecutor dbExecutor = (DbExecutor) springContext.getBean("dbExecutor");
                if (type.equals(callStart))
                {
                    Session event = new Session();
                    event.setWebSession(false);
                    event.setUserName(userName);
                    //event.setComp(comp);
                    event.setPhone(phone.substring(0, ampersand));
                    event.setSessionID(phone.substring(ampersand + 1, phone.length()));
                    phone = event.getPhone();
                    event.setMachineIP(ip);

                    Session oldEvent = currentSessions.AddOrReplace(event);
                    if (oldEvent != null)
                    {
                        previosSessions.AddOrReplace(oldEvent);
                    }

                   if (phone.startsWith("51") || phone.startsWith("99") || phone.startsWith("91") || phone.startsWith("95") || phone.startsWith("98") || phone.startsWith("96") || phone.startsWith("90") || phone.startsWith("14") || phone.startsWith("55") || phone.startsWith("57") || phone.startsWith("58") || phone.startsWith("93") || phone.startsWith("77") || phone.startsWith("97") || phone.startsWith("74") || phone.startsWith("71") || phone.startsWith("92") || phone.startsWith("68") || (phone.startsWith("79") && phone.length()==8))

                   {

                   }

                   else {
                    int length = phone.length();
                    switch (length)
                    {

                        case 9:
                            break;
                        case 8:
                            phone = "2" + phone;
                            event.setPhone(phone);
                            break;
                        case 7:
                            phone = "22" + phone;
                            event.setPhone(phone);
                            break;
                        default:
                            throw new IllegalArgumentException(phone);
                    }
                   }

                    if (phone.startsWith("22") || phone.startsWith("32") || phone.startsWith("34") || phone.startsWith("35") || phone.startsWith("36") || phone.startsWith("37") || phone.startsWith("41") || phone.startsWith("42") || phone.startsWith("43") || phone.startsWith("47") || phone.startsWith("49") ||  phone.startsWith("70"))
                            //(phone.startsWith("79") && phone.length()==9))
                    {
                        event.setDebts(dbExecutor.getDebts(phone));
                        List<AbonentFound> list;
                        if (phone.startsWith("22") || phone.startsWith("32"))
                        {
                            
                        list = dbExecutor.searchOrgByPhone(phone.substring(2));
                        }
                        else

                        {
                            list = dbExecutor.searchOrgByPhone(phone);
                        }
                        if (list == null || list.size() == 0)
                        {
                            if (phone.startsWith("22") || phone.startsWith("32"))
                            {
                            list = dbExecutor.searchIndByPhone(phone.substring(2),null);
                            }
                            else
                            {
                                list = dbExecutor.searchIndByPhone(phone,null);
                            }
                            if (list == null || list.size() == 0)
                            {
                                HashMap map = new HashMap();
                                map.put("CALL_ID", event.getSessionID());
                                map.put("PHONE", phone);
                                dbExecutor.insertDiscoveryPhone(map);
                            }
                        } else
                        {
                            event.setCallType(callTypeOrganization);
                            if (list.size() > 1)
                            {


                                // ?????
                            } else
                            {
                                AbonentFound ab = list.get(0);
                                event.setDisplayName(ab.getLastName());

                               // if (ab.getMainID()==1243015 || ab.getMasterID()==1243015)
                               // {
                               //     event.setCbd(1243015);
                              //  }
                              //  else
                              //  {
                                event.setCbd(ab.getBid());
                              //  }
                            }
                        }
                        if (event.getPhone().equals("222444444") || event.getPhone().equals("322444444"))
                        {


                      event.setComp(dbExecutor.getNotesb());

                      }

                        if (dbExecutor.getNoncharge(phone.substring(2))!=null)
                          {
                      event.setCallType(callTypeNoncharge);
                       }
                    }
                    else
                    {
                        if (comp.equals("M"))
                        {
                            event.setCallType(callTypeMobitel);
                            event.setComp(dbExecutor.getNotemob());


                        }
                        else
                        {
                        event.setCallType(callTypeMobile);
                        }
                        String ph = null;
                        ph=phone;
                        Mymobile m=new Mymobile();

                        m.setPhone(ph);
if(dbExecutor.findMobile(m)!=null)
{
                        event.setDisplayName(dbExecutor.findMobile(m).getNm());
                        event.setSex(dbExecutor.findMobile(m).getSx());
}
}

                    dbExecutor.insertSession(event);

                  
                  // int ltw;
                   //ltw=dbExecutor.getLotwinner().getLw();
                    // if (ltw>=8007)
                     //{
                      //dbExecutor.insertLot(event);
                     //}
                }
                else
                {
                    Session event = currentSessions.get(ip);
                    if (event == null)
                    {
                        log("Unknown error in eriks servlet");
                    } else
                    {
                        event.setWebSession(true);
                        event.setSessionID(dbExecutor.getNextSessionID());
                        event.setChcount(0);
                        event.setDebts("");
                    }
                }

            } else
            {
                log("Error in Erik's message");
                return;
            }
        } catch (IllegalArgumentException ie)
        {
            log("Invalid phone: " + ie.getMessage());
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */


       // try {
         //   Thread.sleep(2000L);
       // } catch (InterruptedException ex) {
         //   Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        //}



           PrintWriter out = response.getWriter();
        try {
            // TODO output your page here
            out.println("<html>");
            out.println("<head>");
           // out.println("<title>Servlet Test</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("ok");
            out.println("</body>");
            out.println("</html>");

        }

        finally {
            out.close();
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
